﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CloudFranceTriple.Models;
using System.Web.Security;

namespace CloudFranceTriple.WebRole.Areas.UserManager.Controllers
{
    public class UserRolesController : Controller
    {
        private cloudfrAboq2RsDMEntities db = new cloudfrAboq2RsDMEntities();

        //
        // GET: /UserManager/UserRoles/Index/UserId

        [Authorize(Roles = "RoleHR")]
        public ActionResult Index(int id = 0)
        {
            ViewBag.UserId = id;
            ViewBag.UserName = db.UserProfile.Find(id).UserName;

            var userRoles = System.Web.Security.Roles.GetRolesForUser(db.UserProfile.Find(id).UserName);
            var result = db.webpages_Roles.Where(role => userRoles.Contains(role.RoleName)).OrderBy(role2 => role2.RoleName);
            var UnlinkedRole = db.webpages_Roles.OrderBy(role => role.RoleName).Except(result);
            ViewBag.Role_Id = new SelectList(UnlinkedRole, "RoleId", "RoleName");
            ViewBag.ShowLinkRole = (UnlinkedRole.ToList().Count() != 0);
            var selectedRoleId = Request.Form["Role_Id"];
            if (selectedRoleId != null)
            {
                return RedirectToAction("Link", "UserRoles", new { id = id, id2 = int.Parse(selectedRoleId.ToString()), area = "UserManager" });
            }
            return View(result.ToList());
        }

        //
        // GET: /UserManager/UserRoles/Link/UserId/RoleId

        [Authorize(Roles = "RoleHR")]
        public ActionResult Link(int id = 0, int id2 = 0)
        {
            var user = db.UserProfile.Find(id);
            var role = db.webpages_Roles.Find(id2);
            if (user == null || role == null)
            {
                return HttpNotFound();
            }
            Roles.AddUserToRole(user.UserName, role.RoleName);
            return RedirectToAction("Index", "UserRoles", new { id = id, area = "UserManager" });
        }

        //
        // GET: /UserManager/UserRoles/Unlink/UserId/RoleId

        [Authorize(Roles = "RoleHR")]
        public ActionResult Unlink(int id = 0, int id2 = 0)
        {
            var user = db.UserProfile.Find(id);
            var role = db.webpages_Roles.Find(id2);
            if (user == null || role == null)
            {
                return HttpNotFound();
            }
            Roles.RemoveUserFromRole(user.UserName, role.RoleName);
            return RedirectToAction("Index", "UserRoles", new { id = id, area = "UserManager" });
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}